//
//  BYTreeNodeCell.m
//  BYTreeView
//
//  Created by Bau-yin on 16/1/6.
//  Copyright (c) 2016年 Bau-yin. All rights reserved.
//

#import "BYTreeNodeCell.h"

@interface BYTreeNodeCell ()
@property (strong, nonatomic) UIButton *foldButton;
@property (strong, nonatomic) UILabel *titleLabel;
@end

@implementation BYTreeNodeCell

#pragma mark - init
- (void)awakeFromNib
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

//- (void)drawRect:(CGRect)rect
//{
//    // 画Cell分割线
//    CGFloat cellHeight;
//    if ([self.nodeDelegate respondsToSelector:@selector(cellHeightAtNode:)])
//    {
//        cellHeight = [self.nodeDelegate cellHeightAtNode:self];
//    }
//    CGContextRef splitLine = UIGraphicsGetCurrentContext();
//    CGContextSetLineWidth(splitLine, 0.6);
//    CGContextSetRGBStrokeColor(splitLine, 0.8, 0.8, 0.8, 1.0);//线条颜色
//    CGContextMoveToPoint(splitLine, 0, cellHeight);    // 节点上面的分割线
//    CGContextAddLineToPoint(splitLine, self.frame.size.width, cellHeight);
//    CGContextStrokePath(splitLine);
//}

#pragma mark - Setter
- (void)setNodeData:(BYTreeNodeData *)nodeData
{
    _nodeData = nodeData;
    [self setupClickButton];
}

#pragma mark - Methods
- (void)setupClickButton
{
    CGFloat cellHeight;
    if ([self.nodeDelegate respondsToSelector:@selector(cellHeightAtNode:)])
    {
        cellHeight = [self.nodeDelegate cellHeightAtNode:self];
    }
    CGRect frame = CGRectMake(0, 0, [UIApplication sharedApplication].keyWindow.bounds.size.width, cellHeight);
    if (self.foldButton == nil)
    {
        frame.origin = CGPointZero;
        self.foldButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.foldButton.frame = self.bounds;
        [self.foldButton addTarget:self action:@selector(actionFoldButton:) forControlEvents:UIControlEventTouchUpInside];
        [self insertSubview:self.foldButton atIndex:100];
    }
    self.foldButton.selected = self.nodeData.expand;
}

#pragma mark - IBAction
- (void)actionFoldButton:(UIButton *)sender
{
    if ([self.nodeDelegate respondsToSelector:@selector(shouldExpandAtSeletedNode:)])
    {
        if ([self.nodeDelegate shouldExpandAtSeletedNode:self] == YES)
        {
            sender.selected = ! sender.selected;
            self.nodeData.expand = sender.selected;
            
            if ([self.nodeDelegate respondsToSelector:@selector(didExpandAtSeletedNode:)])
            {
                [self.nodeDelegate didExpandAtSeletedNode:self];
            }
        }
    }
}

@end
